package com.gpframework.module.controller.wages;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gpframework.common.annotation.Log;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.page.TableDataInfo;
import com.gpframework.common.enums.BusinessType;
import com.gpframework.common.enums.YesNoEnum;
import com.gpframework.common.exception.BaseException;
import com.gpframework.common.utils.poi.ExcelUtil;
import com.gpframework.module.wages.domain.GzFleetMonthlyRecord;
import com.gpframework.module.wages.domain.GzMonthlyPickup;
import com.gpframework.module.wages.domain.GzMonthlyReceiptOfGoods;
import com.gpframework.module.wages.domain.GzMonthlySalaryDetails;
import com.gpframework.module.wages.domain.req.GzMonthlySalaryDetailsAdd;
import com.gpframework.module.wages.domain.req.GzMonthlySalaryDetailsReq;
import com.gpframework.module.wages.domain.req.GzMonthlySalaryDetailsUpdate;
import com.gpframework.module.wages.domain.vo.GzMonthlySalaryDetailsVo;
import com.gpframework.module.wages.service.IGzFleetMonthlyRecordService;
import com.gpframework.module.wages.service.IGzMonthlyPickupService;
import com.gpframework.module.wages.service.IGzMonthlyReceiptOfGoodsService;
import com.gpframework.module.wages.service.IGzMonthlySalaryDetailsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
/**
 * @ClassName GzMonthlySalaryDetailsController
 * @Author gpframework
 * @Date 2024-04-09
 * @Version 1.0.0
 * @Description 月度工资明细Controller
 */
@Validated
@Api(tags = "月度工资明细")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@SuppressWarnings({"rawtypes","unchecked"})
@RequestMapping("/wages/gzMonthlySalaryDetails" )
public class GzMonthlySalaryDetailsController extends BaseController {

    private final IGzMonthlySalaryDetailsService iGzMonthlySalaryDetailsService;

    //拿货月度
    private final IGzMonthlyPickupService iGzMonthlyPickupService;

    //收货月度
    private final IGzMonthlyReceiptOfGoodsService iGzMonthlyReceiptOfGoodsService;

    //车队月度
    private final IGzFleetMonthlyRecordService iGzFleetMonthlyRecordService;

 /**
  * @Description 分页
  * @Author gpframework
  * @Date 2024-04-09
  * @Param gzMonthlySalaryDetails
  * @Return TableDataInfo
 */
    @ApiOperation("列表")
    //@PreAuthorize("@ss.hasPermi('wages:gzMonthlySalaryDetails:list')")
    @GetMapping("/list")
    public TableDataInfo<GzMonthlySalaryDetailsVo> list(GzMonthlySalaryDetailsReq gzMonthlySalaryDetailsReq)
    {
        startPage();
        QueryWrapper<GzMonthlySalaryDetails> lqw = new QueryWrapper<GzMonthlySalaryDetails>();
        gzMonthlySalaryDetailsReq.generatorQuery(lqw,true);
        List<GzMonthlySalaryDetailsVo> list = iGzMonthlySalaryDetailsService.listVo(lqw);
        return getDataTable(list);
    }

    /**
     * @Description 新增
     * @Author gpframework
     * @Date 2024-04-09
     * @Param gzMonthlySalaryDetails
     * @Return TableDataInfo
     */
    @ApiOperation("新增")
    //@PreAuthorize("@ss.hasPermi('wages:gzMonthlySalaryDetails:add')" )
    @Log(title = "添加月度工资明细" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody GzMonthlySalaryDetailsAdd gzMonthlySalaryDetailsAdd) {
        GzMonthlySalaryDetails gzMonthlySalaryDetails = Convert.convert(new TypeReference<GzMonthlySalaryDetails>() {}, gzMonthlySalaryDetailsAdd);
        return toAjax(iGzMonthlySalaryDetailsService.save(gzMonthlySalaryDetails) ? 1 : 0);
    }

    /**
     * @Description 修改
     * @Author gpframework
     * @Date 2024-04-09
     * @Param gzMonthlySalaryDetails
     * @Return TableDataInfo
     */
    @ApiOperation("修改")
    //@PreAuthorize("@ss.hasPermi('wages:gzMonthlySalaryDetails:edit')" )
    @Log(title = "修改月度工资明细" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody GzMonthlySalaryDetailsUpdate gzMonthlySalaryDetailsUpdate) {
        GzMonthlySalaryDetails gzMonthlySalaryDetails = Convert.convert(new TypeReference<GzMonthlySalaryDetails>() {}, gzMonthlySalaryDetailsUpdate);
        return toAjax(iGzMonthlySalaryDetailsService.updateById(gzMonthlySalaryDetails) ? 1 : 0);
    }




    /**
     * @Description 导出
     * @Author gpframework
     * @Date 2024-04-09
     * @Param gzMonthlySalaryDetails
     * @Return TableDataInfo
     */

    //@PreAuthorize("@ss.hasPermi('wages:gzMonthlySalaryDetails:export')" )
    @Log(title = "导出月度工资明细" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(GzMonthlySalaryDetailsReq gzMonthlySalaryDetailsReq) {
        QueryWrapper<GzMonthlySalaryDetails> lqw = new QueryWrapper<GzMonthlySalaryDetails>();
        gzMonthlySalaryDetailsReq.generatorQuery(lqw,true);
        List<GzMonthlySalaryDetailsVo> list = iGzMonthlySalaryDetailsService.listVo(lqw);
        ExcelUtil<GzMonthlySalaryDetailsVo> util = new ExcelUtil<GzMonthlySalaryDetailsVo>(GzMonthlySalaryDetailsVo. class);
        return util.exportExcel(list, "gzMonthlySalaryDetails" );
    }


    @ApiOperation("下载月度工资明细模板")
    //@PreAuthorize("@ss.hasPermi('wages:gzMonthlySalaryDetails:export')" )
    @Log(title = "下载月度工资明细模板" , businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplate" )
    public AjaxResult importTemplate() {
        ExcelUtil<GzMonthlySalaryDetailsVo> util = new ExcelUtil<GzMonthlySalaryDetailsVo>(GzMonthlySalaryDetailsVo.class);
        return util.importTemplateExcel("月度工资明细模板");
    }


    @ApiOperation("导入月度工资明细")
    //@PreAuthorize("@ss.hasPermi('manufacture:employeeevaluation:add')" )
    @Log(title = "导入月度工资明细" , businessType = BusinessType.INSERT)
    @PostMapping("/import")
    @Transactional
    public AjaxResult importList(MultipartFile file) throws Exception {
        if (file == null) {
            return AjaxResult.error("获取不到导入文件");
        }
        boolean excel = ExcelUtil.isExcel(file.getOriginalFilename());
        if (!excel) {
            return AjaxResult.error("导入文件格式错误，请导入excel文件");
        }
        // 导入新数据
        ExcelUtil<GzMonthlySalaryDetailsVo> util = new ExcelUtil<GzMonthlySalaryDetailsVo>(GzMonthlySalaryDetailsVo.class);
        List<GzMonthlySalaryDetailsVo> excelList = util.importCacheExcel(file.getInputStream());
        List<GzMonthlySalaryDetails> list = Convert.convert(new TypeReference<List<GzMonthlySalaryDetails>>() {}, excelList);

        for (int i = 0; i < list.size(); i++) {
            // ！！！导入的excel 名字不能相同
            //绑定 月度工资明细id
            GzMonthlySalaryDetails gzMonthlySalaryDetails = iGzMonthlySalaryDetailsService.getOne(new QueryWrapper<GzMonthlySalaryDetails>()
                    .eq("name", list.get(i).getName())
                    .eq("month", list.get(i).getMonth())
                    .eq("del_status", YesNoEnum.NO.getKey()));
            if (!StringUtils.isEmpty(gzMonthlySalaryDetails))
            {
                list.get(i).setId(gzMonthlySalaryDetails.getId());
            }

            //拿第一个导入人员的月份
            Date monthPickup = list.get(0).getMonth();
            if (monthPickup ==null){
                throw new BaseException("请输入需要进行导入的月份(根据第一个人员月份绩效导入)");
            }

            //拿货月度
            GzMonthlyPickup gzMonthlyPickup = iGzMonthlyPickupService.getOne(new QueryWrapper<GzMonthlyPickup>()
                    .eq("month", monthPickup)
                    .eq("del_status", YesNoEnum.NO.getKey())
                    .last("limit 1"));

            //收货月度
            GzMonthlyReceiptOfGoods gzMonthlyReceiptOfGoods = iGzMonthlyReceiptOfGoodsService.getOne(new QueryWrapper<GzMonthlyReceiptOfGoods>()
                    .eq("month", monthPickup)
                    .eq("del_status", YesNoEnum.NO.getKey())
                    .last("limit 1"));

            //车队月度
            GzFleetMonthlyRecord gzFleetMonthlyRecord = iGzFleetMonthlyRecordService.getOne(new QueryWrapper<GzFleetMonthlyRecord>()
                    .eq("month", monthPickup)
                    .eq("del_status", YesNoEnum.NO.getKey())
                    .last("limit 1"));

            //绑定拿货月度id
            if (gzMonthlyPickup!=null && list.get(i).getMonthlySalaryType().equals("0")){
                list.get(i).setMonthlySalaryId(gzMonthlyPickup.getId());
            }
            //绑定收货月度id
            if (gzMonthlyPickup!=null && list.get(i).getMonthlySalaryType().equals("1")){
                list.get(i).setMonthlySalaryId(gzMonthlyReceiptOfGoods.getId());
            }
            //绑定车队月度id
            if (gzMonthlyPickup!=null && list.get(i).getMonthlySalaryType().equals("2")){
                list.get(i).setMonthlySalaryId(gzFleetMonthlyRecord.getId());
            }

        }

        return iGzMonthlySalaryDetailsService.saveOrUpdateBatch(list) ? AjaxResult.success("导入成功") : AjaxResult.error();
    }



    /**
     * @Description 详情
     * @Author gpframework
     * @Date 2024-04-09
     * @Param gzMonthlySalaryDetails
     * @Return TableDataInfo
     */
    @ApiOperation("详情")
    //@PreAuthorize("@ss.hasPermi('wages:gzMonthlySalaryDetails:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult<GzMonthlySalaryDetailsVo> getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iGzMonthlySalaryDetailsService.getVoById(id));
    }



    /**
     * @Description 删除
     * @Author gpframework
     * @Date 2024-04-09
     * @Param gzMonthlySalaryDetails
     * @Return TableDataInfo
     */
    @ApiOperation("删除")
    @PreAuthorize("@ss.hasPermi('wages:gzMonthlySalaryDetails:remove')" )
    @Log(title = "删除月度工资明细" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iGzMonthlySalaryDetailsService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
